<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :http-request="httpRequest"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>

/*先上传，然后把url给父类更新的表单*/
import {imgSave} from "@/api/img";

export default {
  name: 'uploadCover',
  props: ['blogImgUrl'],
  created() {
    if (this.blogImgUrl!=null){
      this.imageUrl = this.blogImgUrl
    }
  },
  data() {
    return {
      imageUrl: ''
    };
  },
  methods: {
    httpRequest(data){
      /*自定义上传*/

      let formData = new FormData();
      formData.append('file', data.file);
      //使用raw才能正常上传

      let uploadImgUrl = '';
      imgSave(formData).then(
        res=>{
          if (res.code===0) {
            this.$message({
              type: 'success',
              message: '封面上传成功！'
            })
            uploadImgUrl = res.data.imgLocation;
            this.imageUrl = res.data.imgLocation;
          } else {
            this.$message({
              /*上传失败*/
              type: 'error',
              message: res.msg
            })

          }
          this.$emit('submit-url',uploadImgUrl);
        }
      )

    },
    handleAvatarSuccess(res, file) {

    },
    beforeAvatarUpload(file) {
      /*const isJPG = file.type === 'image/jpeg';*/
      const isLt2M = file.size / 1024 / 1024 < 2;

      /* if (!isJPG) {
         this.$message.error('上传头像图片只能是 JPG 格式!');
       }*/
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!');
      // }
      // return isLt2M;
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
